package com.birdboot.core;

import com.birdboot.http.HttpServletRequest;

import java.io.*;
import java.net.Socket;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

/**
 * 该线程的任务是与指定客户端完成HTTP交互
 */
public class ClientHandler implements Runnable{
    private Socket socket;

    public  ClientHandler(Socket socket){
        this.socket = socket;
    }

    @Override
    public void run() {
        // 1、解析请求
        // 1.1 解析请求行
        try {
            HttpServletRequest request = new HttpServletRequest(socket);

        // 2、处理请求
            String path = request.getUri();
            System.out.println("抽象路径："+path);
            // 测试将static目录下的index.html页面包含在一个响应中发送给浏览器，测试浏览器是否可以正常接受
            File baseDir = new File(ClientHandler.class.getClassLoader().getResource(".").toURI());// 定位类加载路径（固定写法）
            File staticFile = new File(baseDir,"static");// 根据类加载路径定位static目录
            //File file = new File(staticFile,"index.html");// 根据static目录定位index.html页面
            File file = new File(staticFile,path);

        // 3、发送响应
            // 将页面包含在响应中发送给浏览器
            /**
             * HTTP/1.1 404 NotFound(CRLF)
             * Content-Type: text/html(CRLF)
             * Content-Length: 2546(CRLF)(CRLF)
             * 1011101010101010101......
             */
            // 1发送状态行
            println("HTTP/1.1 200 OK");
            // 2发送响应头
            println("Content-Type: text/html");
            println("Content-Length: "+file.length());
            // 单独发送回车加换行表达响应头发完了
            println("");
            // 3发送响应正文
            OutputStream out = socket.getOutputStream();
            FileInputStream fis = new FileInputStream(file);
            byte[] data = new byte[1024*10];
            int len;
            while ((len=fis.read(data))!=-1){
                out.write(data,0,len);
            }
        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
        } finally {
            try {
                //遵循Http协议要求，一问一答后关闭连接，finally里面的代码每次运行后都要运行
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    private void println(String line) throws IOException {
        OutputStream out = socket.getOutputStream();
        out.write(line.getBytes(StandardCharsets.ISO_8859_1));
        out.write(13);
        out.write(10);
    }


}
